package interceptor

import (
	"context"
	"fmt"
	"github.com/mitchellh/mapstructure"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"strings"
)

var (
	errMessingMetadata = status.Errorf(codes.InvalidArgument, "missing metadata")
	errInvalidToken    = status.Errorf(codes.Unimplemented, "invalid token")
)

// EnsureValidToken 验证token
func EnsureValidToken(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, errMessingMetadata
	}

	if !valid(md["authorization"], req) {
		return nil, errInvalidToken
	}
	ctx = context.WithValue(ctx, "userId", 1)

	return handler(ctx, req)
}

// valid 验证
func valid(authorization []string, req interface{}) bool {

	var reqMap map[string]interface{}
	err := mapstructure.Decode(req, &reqMap)
	if err != nil {
		fmt.Println("err:", err)
		return false
	}

	if len(authorization) < 1 {
		return false
	}

	token := strings.TrimPrefix(authorization[0], "Bearer ")

	return token == "some-secret-token"
}
